import face_recognition
from PIL import Image
# import numpy as np
from os.path import getsize

localpath = "D:/picture/face/"
filename = "gujiahua.jpg"
filepath = localpath+filename
image = face_recognition.load_image_file(filepath)
face_locations = face_recognition.face_locations(image)

for face_location in  face_locations:
    flag = 1
    top,right,bottom,left =  face_location
    #反复测试最佳的脸部位置
    while flag==1:
        try:
            face_image = image[top:bottom,left:right]
            face_img = Image.fromarray(face_image)
            face_img.save(filepath)
            face_encoding = face_recognition.face_encodings(face_recognition.load_image_file(filepath))[0]
            #压缩图片不大于5kb
            while True:
                if(getsize(filepath)>=5120):
                    w, h = face_img.size
                    # face_img.resize((w//2, h//2),Image.ANTIALIAS)  #缩
                    face_img.thumbnail((h//2,w//2))
                    face_img.save(filepath)
                    continue
                else:
                    break
            flag = 0
        except IndexError:
            top-=1;right+=1;bottom+=1;left-=1
    # face_img.show()
    # w, h = face_img.size
    #压缩图片
    # face_img.resize((w//2, h//2),Image.ANTIALIAS).save(localpath+"chenluqiang1.jpg")

    # f = open(localpath+"index/files.txt",'ab')
    # f.write(("\t"+filename).encode())
    # f.close()


